package com.mccree.cloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: MccRee
 * @Date: 2022/5/31 16:03
 */
@Configuration
@MapperScan(basePackages = {"com.mccree.cloud.dao.mapper"},sqlSessionTemplateRef = "sqlSessionTemplate")
public class DataSourceConfig {
    @Value("${spring.datasource.payment.url}")
    protected String url;
    @Value("${spring.datasource.payment.username}")
    protected String username;
    @Value("${spring.datasource.payment.password}")
    protected String password;
    @Value("${spring.datasource.payment.driverClassName}")
    protected String driverClassName;

    /**本数据源扫描的mapper路径*/
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    /**创建数据源*/
    @Bean(name = "dataSource")
    public DataSource getFirstDataSource() {
        DataSource build =  DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password)
                .build();
        return build;
    }

    /**
     * 开启分页
     * @return
     */
    @Bean(name = "paginationInterceptor")
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setLimit(-1);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    /** MyBatis-plus全局自定义配置 */
    @Bean(name = "globalConfig")
    @ConfigurationProperties(prefix = "mybatis-plus.global-config")
    public GlobalConfig globalConfig(){
        return new GlobalConfig();
    }

    /**创建事务管理器*/
    @Bean("TransactionManger")
    public DataSourceTransactionManager resourceTransactionManger(@Qualifier("dataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**创建SqlSessionTemplate*/
    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate resourceSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**创建SessionFactory*/
    @Bean(name = "sqlSessionFactory")
    @DependsOn("paginationInterceptor")
    public SqlSessionFactory resourceSqlSessionFactory(@Qualifier("globalConfig") GlobalConfig globalConfig, @Qualifier("dataSource") DataSource dataSource, @Qualifier("paginationInterceptor") PaginationInterceptor paginationInterceptor) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        //  增加mybatis的分页插件
        bean.setPlugins(paginationInterceptor);
        //多数据源会使mybatis-plus的配置失效，需要重新set,勿删
        bean.setGlobalConfig(globalConfig);
        return bean.getObject();
    }
}
